const Vue = require('vue')
const fs = require('fs')
const path = require('path')
const express = require('express')
const {
    createBundleRenderer
} = require('vue-server-renderer')

const server = express()
const isDev = process.env.NODE_ENV === 'development'
const devServer = require('./build/dev-server')


const resolve = file => path.resolve(__dirname, file)
let renderer
let devServeReady
if (isDev) {
    devServeReady = devServer({
        templatePath: resolve('./index.html'),
        serverBundlePath: resolve('./dist/vue-ssr-server-bundle.json'),
        clientManifestPath: resolve('./dist/vue-ssr-client-manifest.json'),
        server
    }, ({
        serverBundle,
        clientManifest,
        template
    }) => {
        renderer = createBundleRenderer(serverBundle, {
            template,
            clientManifest
        })
        console.log('构建完毕')
    })
} else {
    const serverBundle = require('./dist/vue-ssr-server-bundle.json')
    const clientManifest = require('./dist/vue-ssr-client-manifest.json')
    const template = fs.readFileSync('./index.html', 'utf-8')
    renderer = createBundleRenderer(serverBundle, {
        template,
        clientManifest
    })
}




server.use('/dist', express.static('./dist'))

const render = async (req, res) => {
    try {
        const html = await renderer.renderToString({
            url: req.url,
            title: 'SSR',
        })
        res.setHeader('Content-Type', 'text/html;charset=utf-8')
        res.end(html)
    } catch (err) {
        if (err) {
            console.log(err)
            res.status(500).end('Internal Server Error')
        }
    }
}
server.get('*', isDev ? async (req, res) => {
    await devServeReady
    render(req, res)
}: render)
server.listen(3000, () => {
    console.log('server listen 3000')
})